package com.wx.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fruits.constant.FruitsConstant;
import com.jfinal.core.Controller;
import com.wx.exception.WxException;
import com.wx.fruits.FruitsRouterCreater;
import com.wx.router.RouterCreater;
import com.wx.util.WxMpUtil;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpMessageInterceptor;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;

public class WxMpController extends Controller {
	static Logger logger = LoggerFactory.getLogger(WxMpController.class);

	/**
	 * 验证微信token方法
	 * 
	 * @throws WxException
	 * @throws IOException
	 */
	public void index() throws WxException, IOException {
		if ("GET".equals(getRequest().getMethod())) {
			getMethod();
		} else if ("POST".equalsIgnoreCase(getRequest().getMethod())) {
			postMethod();
		}
	}

	private void getMethod() throws WxException {
		logger.debug("GET");
		String appName = getPara("appName");
		WxMpService wxMapService = WxMpUtil.getWxMpServiceByAppName(appName);
		// 微信加密签名
		String signature = getPara("signature");
		// 时间戳
		String timestamp = getPara("timestamp");
		// 随机数
		String nonce = getPara("nonce");
		// 随机字符串
		String echostr = getPara("echostr");
		if (wxMapService.checkSignature(timestamp, nonce, signature)) {
			renderText(echostr != null ? echostr : "");
		} else {
			renderText(String.format("微信appName:%s,校验失败", appName));
		}

	}

	private void postMethod() throws WxException, IOException {
		logger.debug("POST");
		String appName = getPara("appName");
		WxMpService wxMpService = WxMpUtil.getWxMpServiceByAppName(appName);
		WxMpXmlMessage msg = xmlFromWp();
		// WxMpMessageRouterExt routerExt = new
		// WxMpMessageRouterExt(wxMapService);
		WxMpMessageRouter router = null;
		logger.info("存session...");

		router = new WxMpMessageRouter(wxMpService).rule().interceptor(new WxMpMessageInterceptor() {
			@Override
			public boolean intercept(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
					WxSessionManager sessionManager) throws WxErrorException {
				sessionManager.getSession(wxMessage.getFromUserName());
				return false;
			}
		}).handler(new WxMpMessageHandler() {
			@Override
			public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context,
					WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
				// TODO Auto-generated method stub
				return null;
			}
		}).end();

		if ("fruits".equals(appName)) {
			RouterCreater creater = new FruitsRouterCreater(new WxMpMessageRouter(wxMpService));

			router = creater.creater();
		}
		router.route(msg);
		renderText("目前没有");
	}

	private WxMpXmlMessage xmlFromWp() throws IOException, UnsupportedEncodingException {
		/** 读取接收到的xml消息 */
		StringBuffer sb = new StringBuffer();
		InputStream is = getRequest().getInputStream();
		InputStreamReader isr = new InputStreamReader(is, "UTF-8");
		BufferedReader br = new BufferedReader(isr);
		String s = "";
		while ((s = br.readLine()) != null) {
			sb.append(s);
		}
		String xml = sb.toString(); // 次
		logger.debug("xml is {}", xml);
		return WxMpXmlMessage.fromXml(xml);
	}

}
